package graph;

import java.awt.geom.Line2D;

import spatial.MBR;
import spatial.SpatialSearchTreeObject;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.LineSegment;

public class GraphEdge implements SpatialSearchTreeObject {

	private long id;
	private GraphNode node1, node2;

	public GraphEdge(long id) {
		this.id = id;
		node1 = null;
		node2 = null;
	}

	public GraphEdge(long id, GraphNode node1, GraphNode node2) {
		this.id = id;
		this.node1 = node1;
		this.node2 = node2;
	}

	@Override
	public MBR getMBR() {
		double minX = Math.min(node1.x, node2.x);
		double maxX = Math.max(node1.x, node2.x);

		double minY = Math.min(node1.y, node2.y);
		double maxY = Math.max(node1.y, node2.y);

		double width = maxX - minX;
		double height = maxY - minY;

		return new MBR(minX, minY, width, height);
	}

	@Override
	public int getNumOfDimensions() {
		return 2;
	}

	@Override
	public double computeDistanceTo(double[] point) {
		Coordinate p0 = new Coordinate(node1.x, node1.y);
		Coordinate p1 = new Coordinate(node2.x, node2.y);
		LineSegment ls = new LineSegment(p0, p1);

		return ls.distance(new Coordinate(point[0], point[1]));
	}

	@Override
	public boolean contains(MBR rect) {
		return this.getMBR().contains(rect);
	}

	@Override
	public long getId() {
		return id;
	}

	@Override
	public boolean intersects(Object obj) {
		if (obj instanceof GraphNode) {
			return getMBR().intersects(((GraphNode) obj).getMBR());
		} else if (obj instanceof GraphEdge) {
			return getMBR().intersects(((GraphEdge) obj).getMBR());
		} else
			return false;
	}

	@Override
	public boolean intersects(MBR r) {
		return this.getMBR().intersects(r);
	}

	@Override
	public boolean isContainedBy(MBR rect) {
		return rect.contains(this.getMBR());
	}

	@Override
	public boolean isOfSameType(SpatialSearchTreeObject obj) {
		if (obj instanceof GraphEdge) {
			return true;
		}
		return false;
	}

	public String toString() { // Always a good idea for debuging
		// JUNG2 makes good use of these.
		return "GE" + id + " (" + node1.x + "," + node1.y + ")--" + "("
				+ node2.x + "," + node2.y + ")";
	}

	public static void main(String[] args) {
		double[] point1 = { 0, 0 };
		double[] point2 = { 2.0, 2.0 };

		double exp = Math.sqrt(2) / 2;
		System.out.println(exp);
		System.out.println(Line2D.ptLineDist(point1[0], point1[1], point2[0],
				point2[1], 1, 0));
	}

}
